package com.ssps.front.ternant.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.ssps.entity.*;
import com.ssps.front.ternant.service.TernantService;
import com.ssps.front.ternant.util.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Hala Zhou
 * @time 2020/07/21 22:19:20
 */
@RestController
@RequestMapping("ternant")
public class TernantController {

    @Autowired
    TernantService ternantService;

    /**
     * 上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值
     */
    @Value("${uploadFile.location}")
    private String uploadFileLocation;

    /**
     * 获取端口号
     */
    @Value("${server.port}")
    private String port;

    Properties pro = new Properties();

    /**
     * 查询用户的所有信息
     *
     * @param request
     * @return
     */
    @RequestMapping("selectOne")
    public Map<String, Object> selectOne(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfos = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            UserInfo loginUserInfo = ternantService.selectOneUserInfo(loginUserInfos.getUiid());
            map.put("loginUser", loginUser);
            map.put("loginUserInfo", loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param info
     * @return
     */
    @RequestMapping("updateUser")
    public Map<String, Object> updateUser(HttpServletRequest request, @RequestBody String info) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            Map<String, String> parse = MyUtils.parse(info);
            loginUserInfo.setAddress(parse.get("address"));
            loginUserInfo.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(parse.get("birthday")));
            loginUserInfo.setUemail(parse.get("uemail"));
            loginUser.setAcount(parse.get("acount"));
            ternantService.updateUser(loginUser);
            ternantService.updateUserInfo(loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 查询用户所有订单
     *
     * @param info
     * @param request
     * @return
     */
    @RequestMapping("selectAllOrders")
    public Map<String, Object> selectAllOrders(@RequestBody String info, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String, String> parse = MyUtils.parse(info);
        Integer page = Integer.parseInt(parse.get("page"));
        page = page <= 0 ? 1 : page;
        try {
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            List<Orders> ordersList = ternantService.selectOrders(loginUserInfo.getUiid(), page);
            PageInfo pageInfo = new PageInfo(ordersList);
            map.put("pageInfo", pageInfo);
            map.put("ordersList", ordersList);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 上传身份证照片
     *
     * @param idCardFront
     * @param idCardBack
     * @param request
     * @return
     */
    @RequestMapping("verified")
    public Map<String, Object> verified(MultipartFile idCardFront, MultipartFile idCardBack, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            String frontName = idCardFront.getOriginalFilename();
            String backName = idCardBack.getOriginalFilename();
            File frontFile = null;
            File backFile = null;
            if (frontName != null && !frontName.trim().equals("")) {
                String suffix = frontName.substring(frontName.lastIndexOf("."));
                frontName = UUID.randomUUID().toString().replace("-", "") + suffix;
                frontFile = new File(uploadFileLocation, frontName);
                idCardFront.transferTo(frontFile);
            }
            if (backName != null && !backName.trim().equals("")) {
                String suffix = backName.substring(backName.lastIndexOf("."));
                backName = UUID.randomUUID().toString().replace("-", "") + suffix;
                backFile = new File(uploadFileLocation, backName);
                idCardBack.transferTo(backFile);
            }
            ternantService.uploadIdCard(MyUtils.getLocalIP() + ":" + port + "/upload/" + frontFile.getName(),
                    MyUtils.getLocalIP() + ":" + port + "/upload/" + backFile.getName(), loginUserInfo.getUiid());
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 查询用户所有的优惠券
     *
     * @return
     */
    @RequestMapping("selectAllCoupon")
    public Map<String, Object> selectAllCoupon(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            List<UserCoupon> userCouponList = ternantService.selectAllCoupon(loginUserInfo.getUiid());
            map.put("userCouponList", userCouponList);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 上传车辆信息
     *
     * @param plateimg
     * @param driverimg
     * @param request
     * @return
     */
    @RequestMapping("uploadPlate")
    public Map<String, Object> uploadPlate(MultipartFile plateimg, MultipartFile driverimg, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            String plateName = plateimg.getOriginalFilename();
            String driverName = driverimg.getOriginalFilename();
            File plateFile = null;
            File driverFile = null;
            if (plateName != null && !plateName.trim().equals("")) {
                String suffix = plateName.substring(plateName.lastIndexOf("."));
                plateName = UUID.randomUUID().toString().replace("-", "") + suffix;
                plateFile = new File(uploadFileLocation, plateName);
                plateimg.transferTo(plateFile);
            }
            if (driverName != null && !driverName.trim().equals("")) {
                String suffix = driverName.substring(driverName.lastIndexOf("."));
                driverName = UUID.randomUUID().toString().replace("-", "") + suffix;
                driverFile = new File(uploadFileLocation, driverName);
                driverimg.transferTo(driverFile);
            }
            ternantService.uploadPlate(MyUtils.getLocalIP() + ":" + port + "/upload/" + plateFile.getName(),
                    MyUtils.getLocalIP() + ":" + port + "/upload/" + driverFile.getName(), loginUserInfo.getUiid());
            map.put("result", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 填写推荐码
     *
     * @param request
     * @param othercode
     * @return
     */
    @RequestMapping("referralCode")
    public Map<String, Object> referralCode(HttpServletRequest request, @RequestBody String othercode) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            Map<String, String> parse = MyUtils.parse(othercode);
            loginUserInfo.setOthercode(parse.get("othercode"));
            ternantService.referralCode(loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 修改用户头像
     *
     * @param img
     * @param request
     * @return
     */
    @RequestMapping("uploadImg")
    public Map<String, Object> uploadImg(MultipartFile img, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            String imgName = img.getOriginalFilename();
            File imgFile = null;
            if (imgName != null && !"".equals(imgName.trim())) {
                String suffix = imgName.substring(imgName.lastIndexOf("."));
                imgName = UUID.randomUUID().toString().replace("-", "") + suffix;
                imgFile = new File(uploadFileLocation, imgName);
                img.transferTo(imgFile);
            }
            loginUserInfo.setImg(MyUtils.getLocalIP() + ":" + port + "/upload/" + imgFile.getName());
            ternantService.updateUserInfo(loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 获取用户所有的车辆信息
     *
     * @param request
     * @return
     */
    @RequestMapping("selectOneInformation")
    public Map<String, Object> selectOneInformation(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            Information information = ternantService.selectOneInformation(loginUserInfo.getUiid());
            map.put("information", information);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 退款申请
     *
     * @param request
     * @param orders
     * @return
     */
    @RequestMapping("refund")
    public Map<String, Object> refund(HttpServletRequest request, @RequestBody Orders orders) {
        Map<String, Object> map = new HashMap<>();
        try {
            ternantService.refund(orders.getPid2());
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 向支付宝网关发送请求，获取支付二维码
     *
     * @param request
     * @param response
     */
    @RequestMapping("alipay")
    public void alipay(HttpServletRequest request, HttpServletResponse response, @RequestBody String info) throws IOException {
        pro.load(TernantController.class.getResourceAsStream("/mypro.properties"));
        // 设置响应内容为html
        response.setContentType("text/html;charset=" + pro.getProperty("charset"));
        // 读取配置文件信息
        AlipayClient alipayClient = new DefaultAlipayClient(pro.getProperty("gatewayUrl"), pro.getProperty("app_id"),
                pro.getProperty("merchant_private_key"), "json", pro.getProperty("charset"),
                pro.getProperty("alipay_public_key"), pro.getProperty("sign_type"));
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(pro.getProperty("return_url"));
        alipayRequest.setNotifyUrl(pro.getProperty("notify_url"));
        // 得到订单中要展示的参数
        // 计算订单总价
        Map<String, String> parse = MyUtils.parse(info);
        // 订单号，必填
        String out_trade_no = UUID.randomUUID().toString().replace("-", "") + "*" + parse.get("uiid");
        // 付款金额，必填
        String total_amount = parse.get("money");
        // 订单名称，必填
        String subject = "Super SPS";
        // 商品描述，可空
        // TODO 串订单信息
        String body = "商品";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        // 存储响应结果
        String result = "";
        try {
            // 使用java代码发送请求
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        writer.write(result);
        writer.close();
    }

    /**
     * 支付成功后的回调函数
     *
     * @param request
     * @param response
     */
    @RequestMapping("notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        String out_trade_no = request.getParameter("out_trade_no");
        String uiid = out_trade_no.substring(out_trade_no.lastIndexOf("*") + 1);
        String money = request.getParameter("total_amount");
        ternantService.recharge(uiid, money);
    }

    /**
     * 成功后返回的页面
     *
     * @param request
     * @param response
     */
    @RequestMapping("success")
    public void success(HttpServletRequest request, HttpServletResponse response) {
        String total_amount = request.getParameter("total_amount");
        String out_trade_no = request.getParameter("out_trade_no");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        String str = "<h1>充值成功！！！</h1>";
        str += "<h2>交易金额：￥" + total_amount + "</h2>";
        str += "<h2>交易编号：" + out_trade_no + "</h2>";
        str += "<h2>关闭当前页面，继续操作</h2>";
        str += "<a href='javascript:void(0)' onclick='jump()'>返回原页面</a>";
        str += "<script>";
        str += "function jump(){location.href=\"http://localhost:63340/ssps/vue/tenant/userinfo.html?1\"};";
        str += "</script>";
        try {
            writer = response.getWriter();
            writer.print(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush();
            writer.close();
        }
    }

    /**
     * 提交评论
     *
     * @param request
     * @param comment
     * @return
     */
    @RequestMapping("addComment")
    public Map<String, Object> addComment(HttpServletRequest request, @RequestBody Comment comment) {
        Map<String, Object> map = new HashMap<>();
        try {
            ternantService.addComment(comment);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 举报功能
     *
     * @param request
     * @param body
     * @return
     */
    @RequestMapping("report")
    public Map<String, Object> report(HttpServletRequest request, @RequestBody String body) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, String> parse = MyUtils.parse(body);
            System.out.println("parse = " + parse);
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            Complaint complaint = new Complaint();
            complaint.setReason(parse.get("reason"));
//            complaint.setResuser(loginUserInfo.getUiid());
            complaint.setResuser(loginUserInfo.getUiid());
            System.out.println("complaint = " + complaint);
            ternantService.report(complaint, parse.get("pid"));
            map.put("result", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping("logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            request.getSession().invalidate();
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 充值套餐
     *
     * @param response
     * @param request
     * @param combo
     * @throws IOException
     */
    @RequestMapping("topup")
    public void topup(HttpServletResponse response, HttpServletRequest request, @RequestBody String combo) throws IOException {
        UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
        pro.load(TernantController.class.getResourceAsStream("/Ruipro.properties"));
        // 设置响应内容为html
        response.setContentType("text/html;charset=" + pro.getProperty("charset"));
        // 读取配置文件信息
        AlipayClient alipayClient = new DefaultAlipayClient(pro.getProperty("gatewayUrl"), pro.getProperty("app_id"),
                pro.getProperty("merchant_private_key"), "json", pro.getProperty("charset"),
                pro.getProperty("alipay_public_key"), pro.getProperty("sign_type"));
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(pro.getProperty("return_url"));
        alipayRequest.setNotifyUrl(pro.getProperty("notify_url"));
        // 得到订单中要展示的参数
        // 计算订单总价
        Map<String, String> parse = MyUtils.parse(combo);
        String total_amount = null;
        if (parse.get("combo").equals("x")) {
            total_amount = "99";

        } else if (parse.get("combo").equals("y")) {
            total_amount = "299";
        }
        Integer uiid = loginUserInfo.getUiid();
        // 订单号，必填
        String out_trade_no = UUID.randomUUID().toString().replace("-", "") + "*" + uiid;
        // 付款金额，必填

        // 订单名称，必填
        String subject = "Super SPS";
        // 商品描述，可空
        // TODO 串订单信息
        String body = "商品";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        // 存储响应结果
        String result = "";
        try {
            // 使用java代码发送请求
            result = alipayClient.pageExecute(alipayRequest).getBody();

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        writer.write(result);
        writer.close();
    }

    /**
     * 套餐充值成功回调函数
     *
     * @param request
     * @param response
     */
    @RequestMapping("notify2")
    public void notify2(HttpServletRequest request, HttpServletResponse response) {
        String out_trade_no = request.getParameter("out_trade_no");
        Integer uiid = Integer.valueOf(out_trade_no.substring(out_trade_no.lastIndexOf("*") + 1));
        String combo = request.getParameter("total_amount");
        ternantService.topup(uiid, combo);
    }

    /**
     * 转账、修改账户余额
     *
     * @param request
     * @param money
     * @return
     */
    @RequestMapping("withdrawMoney")
    public Map<String, Object> withdrawMoney(HttpServletRequest request, @RequestBody String money) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, String> parse = MyUtils.parse(money);
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            ternantService.withdrawMoney(loginUserInfo.getUiid(), parse.get("money"));
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }


}
